// pages/home/cars.js
const App = getApp()
import Kits from '../../utils/kits'
Page({
  data: {
    init: false,
    CustomBar: App.Global.CustomBar,
    types: [{
      name: '推荐',
      sort: 0,
      val: 'RMD'
    }],
    cars: {},
    count: 0,
    auto: 'none',
    seat: 0,
    min: 0,
    max: 0,
    sort: 'Default',

    begin: {
      value: undefined,
      year: '',
      date: '',
      time: '',
    },
    close: {
      value: undefined,
      year: '',
      date: '',
      time: '',
    },
    hdays: '',
    onsite: false,
    area: '',
    addr: '',
    locs: '',
    city: '',
    curType: 'RMD',
    topType: 0,
    sorts: [{
      text: '综合排序',
      value: 'Default'
    }, {
      text: '价格从低到高',
      value: 'PriceAsc'
    }, {
      text: '价格从高到低',
      value: 'PriceDesc'
      // }, {
      //   text: '销量从低到高',
      //   value: 'SaleAsc'
      // }, {
      //   text: '销量从高到低',
      //   value: 'SaleDesc'
    }],
    brands: [],
    brand: {},
  },
  onLoad(options) {
    this.doSetDates(new Date(parseInt(options.begin)), new Date(parseInt(options.close)))
    this.setData({
      area: options.area,
      locs: options.locs,
      addr: options.addr,
      city: options.city,
      onsite: options.onsite === 'true'
    })
    this.setData({
      init: true
    })
    App.doPost({
      uri: '/comm/data/dict',
      body: {
        key: 'serie_type'
      },
      fnSucc: resp => {
        this.setData({
          init: true,
          types: this.data.types.concat(resp.data.items).concat([{
            name: '其他',
            sort: 99999,
            val: 'OTHER'
          }])
        })
        this.execLoad()
      }
    })

  },
  execLoad() {
    console.log(this.data.brand,"carrrr")
    App.doPost({
      uri: '/app/base/biz/car/list',
      body: {   
        city: this.data.city,
        begin: new Date(this.data.begin.value).format('yyyy-MM-dd HH:mm:ss'),
        close: new Date(this.data.close.value).format('yyyy-MM-dd HH:mm:ss'),
        bid: this.data.brand.id || '',
        auto: this.data.auto == 'none' ? undefined : this.data.auto == 'true',
        seat: this.data.seat,
        min: this.data.min,
        max: this.data.max,
        sort: this.data.sort
      },
      fnSucc: resp => {
        resp.data.items.forEach(item => {
          item.price.pdpStr = Kits.fmtMoneyString(item.price.pdp)
          item.price.pmpStr = Kits.fmtMoneyString(item.price.pmp)
          item.price.mdpStr = Kits.fmtMoneyString(item.price.mdp)
          item.price.depositStr = Kits.fmtMoneyString(item.price.deposit)
          item.price.dispStr = Kits.fmtMoneyString(item.price.disp)

        })
        let tids = this.data.types.filter(t => t.val != 'RMD' && t.val != 'OTHER').map(t => t.val)
        let cars = {}
        cars["RMD"] = resp.data.items.filter(c => c.rmd)
        cars["OTHER"] = resp.data.items.filter(c => tids.indexOf(c.type) < 0)
        resp.data.items.forEach(c => {
          if (tids.indexOf(c.type) >= 0) {
            let ccs = cars[c.type] || []
            ccs[ccs.length] = c
            cars[c.type] = ccs
          }
        })
        this.setData({
          cars: cars,
          brands: resp.data.brands,
          count: resp.data.items.length
        })
      },
      fnComp: () => {
        this.setData({
          loading: false
        })
      }
    })
  },
  // 选择地点
  doSelectLocs() {
    let lng = this.data.onsite_locs ? parseFloat(this.data.onsite_locs.split(',')[0]) : undefined
    let lat = this.data.onsite_locs ? parseFloat(this.data.onsite_locs.split(',')[1]) : undefined
    wx.chooseLocation({
      longitude: lng,
      latitude: lat,
      success: (res) => {
        let locs = res.longitude.toFixed(6) + ',' + res.latitude.toFixed(6)
        this.execReadLocation(locs)
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
  // 读取位置信息
  execReadLocation(locs) {
    if (locs == '') {
      return
    }
    App.doPost({
      uri: '/comm/tool/locs/info',
      body: {
        locs: locs
      },
      fnSucc: resp => {
        this.setData({
          addr: resp.data.name,
          area: resp.data.area.code + "",
          locs: locs,
          city: resp.data.city
        })
        this.execLoad()
      }
    })
  },
  // 跳转选择日期界面
  toSelectDate() {
    wx.navigateTo({
      url: `/pages/order/calendar?carid=&begin=${this.data.begin.value}&close=${this.data.close.value}`,
      events: {
        enter: (e) => {
          this.doSetDates(new Date(e.begin), new Date(e.close))
        }
      }
    })
  },
  // 设置日期
  doSetDates(beginTime, closeTime) {
    let begin = {
      value: beginTime.getTime(),
      year: beginTime.format('yyyy'),
      date: beginTime.format('MM月dd日'),
      time: beginTime.format('HH:mm'),
    }
    let close = {
      value: closeTime.getTime(),
      year: closeTime.format('yyyy'),
      date: closeTime.format('MM月dd日'),
      time: closeTime.format('HH:mm'),
    }
    this.setData({
      begin: begin,
      close: close,
      hdays: Kits.getDateMemo(beginTime, closeTime)
    })
    if (this.data.init) {
      this.execLoad()
    }
  },
  // 店家选项卡触发
  doTabChange(e) {
    console.log(e.currentTarget.dataset,"bh")
    this.setData({
      curType: e.currentTarget.dataset.id,
      topType: (parseInt(e.currentTarget.dataset.idx) - 1) * 50
    })
  },

  doCarsScroll(e) {
    let list = this.data.types;
    console.log(list,"list")
    let tabHeight = 0;
    for (let i = 0; i < list.length; i++) {
      let view = wx.createSelectorQuery().select("#main-" + list[i].val)
      if (view) {
        view.fields({
          size: true
        }, data => {
          if (data) {
            list[i].top = tabHeight;
            tabHeight = tabHeight + data.height;
            list[i].bottom = tabHeight;
          }
        }).exec();
      }
    }
  },
  doSetAuto(e) {
    let val = e.currentTarget.dataset.type
    if (this.data.auto == 'none') {
      this.setData({
        auto: val
      })
    } else {
      if (this.data.auto == 'true') {

        this.setData({
          auto: val === 'true' ? 'none' : 'false'
        })
      } else {
        this.setData({
          auto: val === 'false' ? 'none' : 'true'
        })
      }
    }
  },
  doSetSeat(e) {
    let val = e.currentTarget.dataset.type
    if (this.data.seat == 0) {
      this.setData({
        seat: parseInt(val)
      })
    } else {
      if (this.data.seat == 5) {
        this.setData({
          seat: val === '5' ? 0 : 7
        })
      } else {
        this.setData({
          seat: val === '7' ? 0 : 5
        })
      }
    }
  },
  doSetBrand(e) {
    console.log(e.currentTarget.dataset.type)
    let val = e.currentTarget.dataset.type
    this.setData({
      brand: val
    })
    // this.execLoad()
  },
  doSetPrice(e) {
    let min = e.currentTarget.dataset.min
    let max = e.currentTarget.dataset.max
    this.setData({
      min: parseInt(min),
      max: parseInt(max)
    })
  },
  // 筛选确定
  doQuery() {
    // 取消弹窗
    this.selectComponent('#item1').toggle(false)
    this.execLoad()
  },
  doClearMore() {
    this.setData({
      auto: 'none',
      seat: 0,
      min: 0,
      max: 0,
      brand: {}
    })
  },
  // 去下单
  toCreateOrder(e) {
    let car = e.currentTarget.dataset.car
    wx.navigateTo({
      url: `/pages/order/create?carid=${car.id}&begin=${this.data.begin.value}&close=${this.data.close.value}&onsite=${this.data.onsite}&onsite_area=${this.data.area}&onsite_locs=${this.data.locs}&onsite_addr=${this.data.addr}`,
    })
  },


})